﻿using System;
using System.Collections.Generic;
using System.Xml.Linq;
using Renren.Helpers;
using Renren.Models;
using Renren.ViewModels;

namespace Renren.Services
{
    public static class BlogService
    {
        public static void GetBlog(NewsModel news, BlogViewModel blogView)
        {
            var parameters = new Dictionary<string, string>();
            parameters.Add("method", "blog.get");
            if (news.FeedType == FeedType.ShareBlog)
            {
                parameters.Add("id", news.MediaList[0].MediaId.ToString());
                parameters.Add("uid", news.MediaList[0].OwnerId); 
            }
            else if (news.FeedType == FeedType.PostBlog)
            {
                parameters.Add("id", news.SourceId.ToString());
                parameters.Add("uid", news.ActorId.ToString());
            }
            Service.SendRequest(
                parameters,
                result =>
                {
                    var blog = new BlogModel();
                    var root = XElement.Parse(result);
                    var blogNode = root.Child("blog");
                    blog.UpdateTime = blogNode.GetValue<DateTime>("time");
                    blog.Visable = blogNode.GetValue<PrivacyType>("visable");
                    blog.BlogId = blogNode.GetValue<long>("id");
                    blog.UserId = blogNode.GetValue<long>("uid");
                    blog.Name = blogNode.GetValue("name");
                    blog.HeadUrl = blogNode.GetValue("headurl");
                    blog.Title = blogNode.GetValue("title");
                    blog.Content = blogNode.GetValue("content");
                    blog.ViewCount = blogNode.GetValue<long>("view_count");
                    blog.CommentCount = blogNode.GetValue<long>("comment_count");
                    if (blogNode.Child("comment") != null)
                    {
                        foreach (var commentNode in blogNode.Elements("comment", "*"))
                        {
                            var comment = new CommentModel();
                            comment.UpdateTime = commentNode.GetValue<DateTime>("time");
                            comment.CommentId = commentNode.GetValue<long>("id");
                            comment.UserId = commentNode.GetValue<long>("uid");
                            comment.Name = commentNode.GetValue("name");
                            comment.Text = commentNode.GetValue("content");
                            comment.HeadUrl = commentNode.GetValue("headurl");
                            comment.Whisper = commentNode.GetValue<bool>("is_whisper");
                            blog.CommentList.Add(comment);
                        }
                    }
                    blogView.Blog = blog;
                });
        }
    }
}
